<?php
namespace app\api\controller;

use app\api\tool\Client;
use app\common\controller\RestBase;
use think\Config;
use think\Db;
use think\Loader;
use think\Request;

class App extends RestBase
{
    protected $responceCode = null;

    protected $request = null;
//    缓存平台信息
    protected $platform = null;
//    缓存会员信息
    protected $member = null;

    protected $apptoken=null;

    protected $membertoken=null;

    protected $noSign = false;

    protected $user_id;
    protected $token;
	protected $noNeedController = ['Login','News','Major','School','Index','Temp'];

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        // 允许的头信息
        header('Access-Control-Allow-Headers: X-Requested-With, Content-Type,Token,Userid,Province,Xkprovince');
        // 允许的请求方法
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        $this->responceCode = config("api_code");
        $this->request = Request::instance();
        $this->user_id = $this->request->header('userid');
        $this->token = $this->request->header('token');
        $this->province_id = $this->request->header('province');
        $this->xk_province_id = $this->request->header('xkprovince');
		$controller = $this->request->controller();
		if(in_array($controller,$this->noNeedController)){
			if($this->noWhite()){
				$this->checkToken($this->user_id,$this->token);
			}
		}else{
			if(!$this->White()){
				$this->checkToken($this->user_id,$this->token);
			}
		}
        
    }
	protected function noWhite()
    {
        list($module, $controller, $action, $className) = $this->getCurrentController();
        if (method_exists($className, 'NoWhiteList')) {
            $nowhitelist = $className::NoWhiteList();
            if (!is_array($nowhitelist)) return false;
            foreach ($nowhitelist as $item) {
                if (strtolower($module . '\\' . $controller . '\\' . $item) == strtolower($module . '\\' . $controller . '\\' . $action)) {
                    return true;
                }
            }
        }
        return false;
    }
	protected function White()
    {
        list($module, $controller, $action, $className) = $this->getCurrentController();
        if (method_exists($className, 'WhiteList')) {
            $whitelist = $className::WhiteList();
            if (!is_array($whitelist)) return false;
            foreach ($whitelist as $item) {
                if (strtolower($module . '\\' . $controller . '\\' . $item) == strtolower($module . '\\' . $controller . '\\' . $action)) {
                    return true;
                }
            }
        }
        return false;
    }
	
    protected function getCurrentController()
    {
        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();
        if (strstr($controller, '.'))
            $controllerv1 = str_replace('.', '\\', $controller);
        else
            $controllerv1 = $controller;
        $className = 'app\\' . $module . '\\controller\\' . $controllerv1;
        return [$module, $controller, $action, $className];
    }
    /**
     * 检查token
     * @return bool
     */
    protected function checkToken($user_id, $token)
    {
        $config = cache('db_config_data');

        if(!$config){
            $config = load_config();
            cache('db_config_data',$config);
        }
        //获取token
		if (!isset($user_id) || !isset($token)|| empty($user_id) || empty($token)){
			
			return self::return_err_json(1001,'请登录客户端');
        }
		$member = Db::name("member")->where('id',$user_id)->field('id,is_upprofile')->find();
        if( empty($member) ) return self::return_err_json(1002,'用户不存在');
        $this->user_is_upprofile = $member['is_upprofile'];
        $result = Db::name("member_token")->where('user_id',$user_id)->find();
        if( empty($result) ) return self::return_err_json(1002,'用户不存在');
        $time = time();
        if( $result['expire_time'] < $time ) return self::return_err_json(1003,'用户token已过期，请重新登录');
        if( $result['token'] != $token ) return self::return_err_json(1004,'token错误，请重新登录');
        if( ($result['expire_time']-$time) < 60*60*24*3 ){
            Db::name("member_token")->where(['user_id'=>$user_id])->update(["expire_time"=>$time+60*60*24*7]);
        }

    }
	

	
	protected static function return_err_json($errorCode, $msg="", $data="")

    {

        $returnData['code'] = $errorCode;

        $returnData['data'] = $data;

        $returnData['msg'] = $msg;

        exit(json_encode($returnData,JSON_UNESCAPED_UNICODE));

    }

	protected function return_json($code, $msg, $res)
	{
		$data['code'] = $code;
		$data['msg'] = $msg;
		if($res !="" ){
			$data['data'] = $res;
		}
		return json_encode($data, JSON_UNESCAPED_UNICODE);
	}
    /**
     * 获取输出结果
     * @param int $code 为整数：自定义返回数据，为字符串，返回api_code定义数据，为数组，直接返回定义好的格式
     * @param string $msg
     * @param array $data
     * @return \think\Response
     */
    protected function show($code = 0, $msg = '', $data = array())
    {
        $result = [];
        if (is_int($code)) {//默认为自定义消息响应
            $result['code'] = $code;
            $result['msg'] = $msg;
            $result['data'] = $data;
        } else if (is_string($code)) {//默认为api_code中的消息响应
            if (isset($this->responceCode[$code])) {
                $result = $this->responceCode[$code];
                $result['data'] = $data;
            } else {
                $result['code'] = 0;
                $result['msg'] = $code;//把未知错误信息作为提示
                $result['data'] = $data;
            }

        } else if (is_array($code)) {//数组，可能是api_code消息,也有可能是自定义消息
//            判断提示消息是否来自api_code
            $result = $code;
            if (isset($this->responceCode[$code['msg']])) {

                $tempcode = $this->responceCode[$code['msg']];
                if (empty($tempcode)) {
                    $tempcode = $this->responceCode['unknow_error'];
                }
                if ($code['code'] == 1) {//成功的代码只有一个，只利用其提醒消息msg
                    $result['msg'] = $tempcode['msg'];
                } else {
                    $result['msg'] = $tempcode['msg'];
                    $result['code'] = $tempcode['code'];
                }
            }

            if (!empty($result['data'])&&is_array($result['data'])) {
                $data = array_merge($result['data'], $data);
                $result['data'] = $data;
            }
            
        }
        return $this->showResult($result);


    }

    /**
     * 获取成功响应
     * @param array $data
     * @return mixed
     */
    protected function success($msg = 'success', $data = array())
    {
        if(is_string($msg)){
            if (isset($this->responceCode[$msg])) {
                return $this->show(200,$msg, $data);
            }else{
                return $this->show(200,$msg, $data);
            }
        }else if(is_array($msg)){
            return   $this->show('success','', $msg);
        }


    }

    /**
     * 获取错误响应
     * @param array $data
     * @return mixed
     */
    protected function error($msg = 'error', $data = array())
    {
        if(is_string($msg)){
            if (isset($this->responceCode[$msg])) {
                return $this->show(300,$msg, $data);
            }else{
                return $this->show(300,$msg, $data);
            }
        }else if(is_array($msg)){
            return   $this->show('error','', $msg);
        }
    }

    protected function noLogin($msg = 'no login', $data = array())
    {
        if(is_string($msg)){
            if (isset($this->responceCode[$msg])) {
                return $this->show(202,$msg, $data);
            }else{
                return $this->show(202,$msg, $data);
            }
        }else if(is_array($msg)){
            return   $this->show('no login','', $msg);
        }
    }
	
    public function build_order_no(){
		return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	}

    /**
     * 应用初始化接口
     * 1.查询系统信息
     * 2.查询版本信息
     * 3.查询广告信息
     *
     */
    /*public function init()
    {
        $validate = Loader::validate("App");
        $param=post();
        if (!$validate->scene("init")->check($param)) {
            return $this->error($validate->getError());
        }

        $data = service('App')->getInitInfo($param['device_type'], $param['version']);
        return $this->success("初始化成功", $data);

    }*/

    /**
     * 应用更新接口
     */
    /*public function update()
    {

    }*/

    /**
     * 检查登录，对需要用户登录的地方调用该函数
     * 如未登录，则强制性退出
     * 若登录，返回会员信息
     */
  /*  protected function checkLogin()
    {
        $member = $this->getMember();
        if ($member) {
            return $member;
        } else {
            $this->ajaxReturn($this->responceCode['login_tip_error']);
        }
    }*/

    /**
     * 检查是否有平台信息
     */
    /*protected function checkPlatform()
    {
        $platform = $this->getPlatform();
        if (!$platform) {
            $this->ajaxReturn($this->responceCode['platform_error']);
        }else{
            return $platform;
        }
    }*/



   /* protected function getMember()
    {
        if (!$this->member) {
            $member_token = input("param.membertoken");
            $memberService = service('Member');
            $member = $memberService->where(['member_token' => $member_token, 'token_outtime' => ['>', time()]])->find();
            if ($member) {
                Client::$member=$member;
                $this->member = $member;
            } else {
                $this->member = null;
            }
        }
        return $this->member;

    }*/


    /**
     * @param $data 验证数据
     * @param $validate 验证器
     * @param bool $scene 验证场景
     * @return bool
     */
    protected function validate($data,$validate,$scene=false){
        $validate = Loader::validate($validate);
        if($scene){
            $validate->scene($scene);
        }
        $res = $validate->check($data);
        if (!$res) {
            return $validate->getError();
        }else{
            return false;
        }
    }


}
